# crypto-tool/src/algorithms/chacha.py
from Crypto.Cipher import ChaCha20
import base64

def chacha_encrypt(text, key):
    key = key.encode('utf-8')
    cipher = ChaCha20.new(key=key)
    text_bytes = text.encode('utf-8')
    encrypted_bytes = cipher.encrypt(text_bytes)
    nonce = cipher.nonce
    encrypted_text = base64.b64encode(nonce + encrypted_bytes).decode('utf-8')
    return encrypted_text

def chacha_decrypt(text, key):
    key = key.encode('utf-8')
    encrypted_bytes = base64.b64decode(text)
    nonce = encrypted_bytes[:ChaCha20.nonce_size]
    ciphertext = encrypted_bytes[ChaCha20.nonce_size:]
    cipher = ChaCha20.new(key=key, nonce=nonce)
    decrypted_bytes = cipher.decrypt(ciphertext)
    decrypted_text = decrypted_bytes.decode('utf-8')
    return decrypted_text